package com.ryi.life.web.controller;

import com.ryi.life.mapper.UserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;

/**
 * Created by heshun on 15-12-30.
 */
@Controller
public class IndexController {
    @Resource
    UserMapper userMapper;

    @RequestMapping("go")
    public String go() {
        Subject subject = SecurityUtils.getSubject();
        System.out.println(subject.isPermitted("index:go"));
        return "home";
    }

    @RequestMapping("index")
    public String index() {
        Subject subject = SecurityUtils.getSubject();
        System.out.println(subject.isPermitted("index:index"));
        return "index";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public void toLoginHtml() {
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String root() {
        return "redirect:/home";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(String username, char[] password, Model model, boolean rememberMe) {

        //1. 接受提交的当事人和证书：
        AuthenticationToken token = new UsernamePasswordToken(username, password, rememberMe);

        //2. 获取当前Subject：
        Subject currentUser = SecurityUtils.getSubject();

        String message;
        //3. 登录：
        try {
            // 登录验证
            currentUser.login(token);
            return "redirect:/home";
        } catch (UnknownAccountException uae) {
            uae.printStackTrace();
            message = "用户名或密码不正确";
        } catch (IncorrectCredentialsException ice) {
            ice.printStackTrace();
            message = "用户名或密码不正确";
        } catch (LockedAccountException lae) {
            lae.printStackTrace();
            message = lae.getMessage();
        } catch (ExcessiveAttemptsException eae) {
            eae.printStackTrace();
            message = "用户名或密码错误次数过多";
        } catch (AuthenticationException ae) {
            ae.printStackTrace();
            //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
            message = "用户名或密码不正确";
        }
        model.addAttribute("message", message);
        return "login";
    }


    @RequiresPermissions("index:home")
    @RequestMapping("home")
    public void home() {
    }

    @RequestMapping("unauthorized")
    public void unauthorized() {
    }


}
